<template>
    <el-dialog :close-on-click-modal="false" :title="titleMap" v-model="visible" :width="600" destroy-on-close
        @closed="$emit('closed')">
        <el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="120px" label-position="right">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="①交付方式" prop="listenType">
                        <el-select v-model="form.listenType" placeholder="请选择交付方式" clearable filterable style="width: 100%;">
                            <el-option label="线上" :value="1"></el-option>
                            <el-option label="机构" :value="2"></el-option>
                            <el-option label="上门" :value="3"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="②学员姓名" prop="userId">
                        <el-select
                            style="width: 100%;"
                            v-model="form.userId"
                            filterable
                            remote
                            clearable
                            placeholder="请输入学员姓名搜索"
                            :remote-method="searchUserHander"
                            @change="selectUserFun"
                            :loadings="userLoading">
                                <el-option
                                    v-for="item in userList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                    :disabled="item.disabled">
                                    <span style="float: left">{{ item.name }}</span>
                                    <span style="float: right; color: #8492a6;" v-if="form.courseType == 1">{{ item.classHour30 }}</span>
                                    <span style="float: right; color: #8492a6;" v-if="form.courseType == 2">{{ item.classHour60 }}</span>
                                    <span style="float: right; color: #8492a6;" v-if="form.courseType == 3">{{ item.classHour120 }}</span>
                                </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="form.courseType == 4 ? '③体验课程' : '③课程名称'" prop="courseId" v-if="form.courseType == 4">
                        <el-select v-model="form.courseId" placeholder="请选择" clearable filterable style="width: 100%;">
                            <el-option :label=" item.course ? item.course.name : item.name" :value="item.course ? item.course.id : item.id" v-for="item in userCourses">
                                <span style="float: left;">{{ item.course ? item.course.name : item.name }}</span>
                                <span style="float: right; color: red;" v-if="item.course">{{ item.course.learnNum + '/' + item.course.words }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="③课程名称" prop="courseId" v-if="form.courseType != 4">
                        <el-button type="primary" @click="addCourseFun" size="small">选择课程</el-button>
                        <el-button type="text" v-if="selectedCourses && selectedCourses.length">已选择{{selectedCourses.length}}个课程</el-button>
			        </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="visible = false">取 消</el-button>
            <el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
        </template>
    </el-dialog>

    <courseSelectDom 
		ref="courseSelectDom" 
		@submit="submitAddCourse" 
		v-if="dialog.course" 
		@close="dialog.course = false"
        :userId="form.userId"
		:treeSearch="{type: '2'}"
		:defaultSearch="{containLearnNum: 1, courseStatus: '1', status: '1', userId: form.userId}"
	></courseSelectDom>
</template>

<script>
import courseSelectDom from './courseSelectDom.vue'
export default {
    emits: ['success', 'closed'],
    components: {
		courseSelectDom
	},
    data() {
        return {
            mode: "add",
            titleMap: '填写交付方式、学员姓名和课程名称',
            visible: false,
            isSaveing: false,
            userLoading: false,
            dialog: {
                course: false,
			},
            //表单数据
            form: this.getDefaultRuleForm(),
            //验证规则
            rules: {
                listenType: [
                    { required: true, message: '请选择交付方式', trigger: 'change' },
                ],
                userId: [
                    { required: true, message: '请选择学员', trigger: 'change' },
                ],
                courseId: [
                    { required: true, message: '请选择课程', trigger: 'change' },
                ]
            },
            userList: [],
            userCourses: [],
            selectedCourses: []
        }
    },
    mounted() {
    },
    methods: {
        //显示
        open(titleMap) {
            if (titleMap) {
                this.titleMap = titleMap
            }
            this.visible = true;
            return this
        },
        //选择课程弹窗
        addCourseFun(){
            if (!this.form.userId) {
                this.$notify.error('请先选择学员')
                return false
            }
            this.dialog.course = true
            this.$nextTick(() => {
                let arr = JSON.parse(JSON.stringify(this.selectedCourses))
                this.$refs.courseSelectDom.open(arr || [])
            })
		}, 
        async submitAddCourse(data) {
            let ids = data.map(item => { return item.course.id })
            this.dialog.course = false
            this.form.courseId = ids[0]
            this.selectedCourses = data
        },
        //表单提交方法
        submit() {
            this.$refs.dialogForm.validate(async (valid) => {
                if (!valid) {
                    return false
                }

                let data = {}
                for (let key in this.form) {
                    data[key] = this.form[key]
                }

                if (this.form.courseType == 4) {
                    data.courseId = 0
                    data.courseCategoryId = this.form.courseId
                }

                try {
                    this.isSaveing = true;
                    await this.$API.appointment.addAppointment.post(data).then(res => {
                        if (res.error != 0) {
                            this.$notify.error(res.message)
                            return false
                        }
                        this.$emit('success', this.form, this.mode)
                        this.visible = false;
                        this.$notify.success("保存成功")
                    })
                   
                } finally {
                    this.isSaveing = false;
                }
            })
        },
        //表单注入数据
        setData(data) {
            let oldForm = this.form
            if (oldForm && oldForm.courseType != data.courseType) {
                this.form.courseId = null
                this.form.userId = null
                this.selectedCourses = []
            }
            this.form.courseType = data.courseType
            let teachers = []
            data.teachers.forEach(item => {
                teachers.push({
                    id: item.teacher.id,
                    startTime: item.startTime,
                })
            })
            this.form.teachers = teachers  
            this.searchUserHander()
            return this
        },
        getDefaultRuleForm() {
            return {
                id: null,
                userId: '',
                teachers: [],
                courseId: null,
                courseType: '',
                listenType: ''
            }
        },
        searchUserHander(query) {
            if (!this.form.courseType) {
                return false
            }
            this.userLoading = true;
            let params = {
                name:query, 
                courseType: this.form.courseType
            }
            if (this.form.courseType == 4) {
                params.courseType = 0
            }
            this.$API.user.listByName.get(params).then((res) => {
                let _data = []
                res.data.forEach(ele => {
                    if (this.form.courseType == 1) {
                        ele.disabled = ele.classHour30 == 0 ? true : false
                    }else if (this.form.courseType == 2) {
                        ele.disabled = ele.classHour60 == 0 ? true : false
                    }else if (this.form.courseType == 3) {
                        ele.disabled = ele.classHour120 == 0 ? true : false
                    }else {
                        ele.disabled = false
                    }
                    _data.push(ele)
                })
                this.userList = _data
            }).finally(() => {
                this.userLoading = false
            });
        },
        selectUserFun() {
            if (this.form.courseType == 4) {
                this.getCourseCategory()
            }
        },
        getUserCourseHander() {
            if (!this.form.userId) {
                return false
            }
            this.$API.user.course.all.get({
                userId: this.form.userId,
                status: 1,
                courseStatus: 1
            }).then((res) => {
                this.userCourses = res.data
            })
        },
        getCourseCategory() {
            this.$API.course.category.all.get({
            }).then((res) => {
                this.userCourses = res.data
            })
        },
    }
}
</script>

<style>
</style>
